/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * jdl_add_activity.java
 *
 * Created on Aug 26, 2010, 7:35:13 AM
 */

package GUI;

import config.Database_function;
import config.Function;
import config.User_function;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author RYUDO
 */
public class jdl_add_edit_activity extends javax.swing.JDialog {
    ResultSet activity;
    String ChildID;
    Vector tblTitle;
    Vector tblData;
    /** Creates new form jdl_add_activity */
    public jdl_add_edit_activity(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }

    public jdl_add_edit_activity(java.awt.Frame parent, boolean modal,ResultSet activity,String ChildID) {
        super(parent, modal);
        initComponents();
         Function.Windows_centered(this.getWidth(), this.getHeight(), this);
        this.activity = activity;
        fillComActivity();       
        this.btnEdit.setEnabled(false);
        this.btnDelete.setEnabled(false);
        this.ChildID = ChildID;
        fillTable();
    }
    
    private void fillComActivity() {
        try {
            this.comActivity.removeAllItems();
            while (this.activity.next()) {
                this.comActivity.addItem(this.activity.getString("ActivityName"));
            }
            if(this.comActivity.getItemCount() == 0) {
                this.comActivity.addItem("No activity available");
            }
        } catch (SQLException ex) {
            Logger.getLogger(jdl_add_edit_activity.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void fillTable() {
        tblTitle = new Vector();
        tblData = new Vector();
        tblTitle.add("ChildID");
        tblTitle.add("ActivityName");
        try {

            ResultSet rs = User_function.get_tbl_Activity_Child(ChildID);
            rs.beforeFirst();
            while (rs.next()) {
                Vector temp = new Vector();
                temp.add(rs.getString(2));
                temp.add(User_function.get_activity_name_by_id(rs.getString(1)));
                tblData.add(temp);
            }
            this.tbl_listActivity.setModel(new DefaultTableModel(tblData, tblTitle));
        } catch (SQLException ex) {
            Logger.getLogger(jdl_add_edit_activity.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbl_listActivity = new javax.swing.JTable();
        jPanel2 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        comActivity = new javax.swing.JComboBox();
        btnAdd = new javax.swing.JButton();
        btnEdit = new javax.swing.JButton();
        btnDelete = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Add/Edit Activity");

        jPanel1.setBackground(new java.awt.Color(213, 228, 242));

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18));
        jLabel1.setForeground(new java.awt.Color(9, 32, 90));
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Add/Edit Activity For Child");
        jLabel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        tbl_listActivity.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null},
                {null, null},
                {null, null},
                {null, null}
            },
            new String [] {
                "Child ID", "Activity Name"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tbl_listActivity.setGridColor(new java.awt.Color(213, 213, 213));
        tbl_listActivity.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tbl_listActivityMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tbl_listActivity);

        jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jPanel2.setOpaque(false);

        jLabel2.setText("Available Activity:");

        comActivity.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        btnAdd.setText("Add");
        btnAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddActionPerformed(evt);
            }
        });

        btnEdit.setText("Update");
        btnEdit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditActionPerformed(evt);
            }
        });

        btnDelete.setText("Delete");
        btnDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeleteActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(comActivity, javax.swing.GroupLayout.PREFERRED_SIZE, 156, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnAdd, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnEdit, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnDelete, javax.swing.GroupLayout.DEFAULT_SIZE, 119, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(comActivity, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnAdd)
                    .addComponent(btnEdit)
                    .addComponent(btnDelete))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 624, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 624, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 216, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void tbl_listActivityMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbl_listActivityMouseClicked
        if(this.tbl_listActivity.getSelectedRow() >= 0) {
            this.btnEdit.setEnabled(true);
            this.btnDelete.setEnabled(true);
        } else {
            this.btnEdit.setEnabled(false);
            this.btnDelete.setEnabled(false);
        }
    }//GEN-LAST:event_tbl_listActivityMouseClicked

    private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
        try {
            Connection cn = Database_function.setConnection();
            PreparedStatement pst = cn.prepareStatement("INSERT INTO tbl_Activity_Child (ActivityID,ChildID)VALUES (?,?)");
            pst.setString(2, ChildID);
            pst.setString(1, User_function.get_activity_id_by_name(this.comActivity.getSelectedItem().toString()));
            if(pst.executeUpdate() != 0) {
                 JOptionPane.showMessageDialog(this, "Insert successfully");
                 this.fillTable();
            } else {
                    JOptionPane.showMessageDialog(this, "There's some problem with the database");
             }
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this, "Error ! Make sure that you are not enter the duplicate activity");
            ex.printStackTrace();
        }
    }//GEN-LAST:event_btnAddActionPerformed

    private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed
        int selection = this.tbl_listActivity.getSelectedRow();
        if(selection != -1) {
             Vector temp = new Vector();
              temp = ((Vector) tblData.get(selection));
               int response = JOptionPane.showConfirmDialog(null, "Are you sure to delete this activity ?","Confirm",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);
                if(response == JOptionPane.YES_OPTION) {
                Statement st = null;
                try {
                    Connection cn = Database_function.setConnection();
                    st = cn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
                    if (st.executeUpdate("DELETE FROM tbl_Activity_Child  WHERE ActivityID = "+User_function.get_activity_id_by_name(temp.get(1).toString())) != 0) {
                        JOptionPane.showMessageDialog(null, "Activity deleted successfully");
                        fillTable();
                    } else {
                        JOptionPane.showMessageDialog(null, "No activity was deleted, please check again");
                    }
                } catch (SQLException ex) {
                    Logger.getLogger(jdl_add_edit_activity.class.getName()).log(Level.SEVERE, null, ex);
                } finally {
                    try {
                        st.close();
                    } catch (SQLException ex) {
                        Logger.getLogger(jdl_add_edit_activity.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        }
    }//GEN-LAST:event_btnDeleteActionPerformed

    private void btnEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditActionPerformed
         int selection = this.tbl_listActivity.getSelectedRow();
        if(selection != -1) {
            try {
                Vector temp = new Vector();
                temp = ((Vector) tblData.get(selection));
                 Connection cn = Database_function.setConnection();
                PreparedStatement pst = cn.prepareStatement("UPDATE tbl_Activity_Child SET ActivityID = ? WHERE ChildID = ?");
                pst.setString(2, ChildID);
                pst.setString(1, User_function.get_activity_id_by_name(this.comActivity.getSelectedItem().toString()));
                if(pst.executeUpdate() != 0) {
                 JOptionPane.showMessageDialog(this, "Update successfully");
                 this.fillTable();
            } else {
                    JOptionPane.showMessageDialog(this, "There's some problem with the database");
             }
            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(this, "Error ! Make sure that you are not enter the duplicate contract");
                Logger.getLogger(jdl_add_edit_activity.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_btnEditActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                jdl_add_edit_activity dialog = new jdl_add_edit_activity(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnDelete;
    private javax.swing.JButton btnEdit;
    private javax.swing.JComboBox comActivity;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tbl_listActivity;
    // End of variables declaration//GEN-END:variables

}
